<?php

namespace app\lib\MessageBus\works;

use app\common\logic\OrderCallbackLogic;
use app\common\model\activity\RechargeActivity;
use app\common\model\click\UserCallback;
use app\common\model\order\Order;
use app\common\model\promotion\PromotionLink;
use app\common\model\return_rule\ReturnRule;
use app\common\model\user\User;
use app\common\service\media\MediaService;
use app\lib\MessageBus\base\AbstractWork;

class OrderReturnCallback extends AbstractWork
{
    /**
     * 订单回传
     *
     * @param array $message
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handler($message)
    {
        dump("订单回传开始 订单ID" . $message['order_id'] . date("Y-m-d H:i:s"), $message);
        $order           = Order::where('id', $message['order_id'])->findOrEmpty();
        $user            = User::where('id', $order->user_id)->findOrEmpty();
        $userCallback    = UserCallback::where('user_id', $order->user_id)->findOrEmpty();
        $source          = $order->source ?? 0;
        $promotionLinkId = $user->promotion_link_id ?? 0;
        $returnRule      = ReturnRule::where('promotion_link_id', $promotionLinkId)->findOrEmpty();

        $message['user_id']           = $order->user_id;
        $message['promotion_link_id'] = $promotionLinkId;
        $payIsHc = true;
        //判断如果是旧粉，不回传   旧粉=总粉-（新粉+归因分）
        if ($user->is_new_user==1){
            $payIsHc = false;
            dump("老粉订单不回传 订单ID" . $message['order_id']);
        }
        if ($order->type == 7&&$payIsHc ==true) {
            dump("订单为活动订单,判断是否回传 订单ID" . $message['order_id']);
            // 把活动产生的充值更新上去
            $rechargeActivity = RechargeActivity::where('id', $order->activity_id)->findOrEmpty();
            if (!$rechargeActivity->isEmpty()) {
                $rechargeActivity->recharge_num         += 1;
                $rechargeActivity->accumulated_recharge += $order->money;
                $rechargeActivity->save();
            }
            if ($returnRule->activity_order == 1) {
                dump("订单为活动订单,回转规则配置活动订单扣单不回传 订单ID" . $message['order_id']);
                $payIsHc = false;
            }
        }

        if ($payIsHc) {
            dump("走回传规则判断是否回传开始 订单ID" . $message['order_id']);
            $payIsHc = OrderCallbackLogic::payIsHc($promotionLinkId, $userCallback, $order);
            dump("走回传规则判断是否回传完成 订单ID" . $message['order_id']);
        }

        MediaService::payment($message, $userCallback, $user, $order, $source, $returnRule,$payIsHc);

        // 判断是否上传关键行为 如果为1，判断是否为用户首次下单  新：用户自然日的第一笔充值回传关键行为
        if ($returnRule->key_behaviors == 1 && $user->paynum > 0) {
            MediaService::keyAction($message, $userCallback, $order, $source);
        } else {
            dump("订单规则配置不回传关键行为 订单ID" . $message['order_id']);
        }

        dump("订单回传结束 订单ID" . $message['order_id'] . date("Y-m-d H:i:s"));
    }

}
